package com.love.marriage.common.handler;

import com.love.marriage.cloud.service.AliyunDyplsService;
import com.love.marriage.common.redisKey.VirtualNumberKey;
import com.love.marriage.config.AliyunDyplsConfig;
import com.love.marriage.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class RedisKeyExpirationListener implements MessageListener {

    private final RedisUtils redisUtils;

    private final AliyunDyplsService aliyunDyplsService;

    private final AliyunDyplsConfig aliyunDyplsConfig;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        // 检查键名是否匹配指定类型
        log.info("key info: {}", VirtualNumberKey.virtualNumberBindingKey.getPrefix() + ":");
        if (expiredKey.startsWith(VirtualNumberKey.virtualNumberBindingKey.getPrefix() + ":")) {
            System.out.println("virtualNumberBindingKey key expired: " + expiredKey);
            handleOrderExpiredKey(expiredKey);
        } else {
            System.out.println("Other key expired: " + expiredKey);
        }
    }

    private void handleOrderExpiredKey(String key) {
        // 处理以 "order:" 为前缀的键过期逻辑
        log.info("Handling expired order key: " + key);
        String phone = key.replace(VirtualNumberKey.virtualNumberBindingKey.getPrefix() + ":", "");
        String[] split = phone.split(":");
        try {
            aliyunDyplsService.unBindPhone(aliyunDyplsConfig.getPoolKey(), split[3], split[1]);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}